<?php
namespace app\index\controller;

use app\index\Controller;
use think\Db;

class Account extends Controller
{
    //主账户列表
    public function index()
    {
        if ($this->request->isAjax()) {
            $id       = $this->request->post('id');
            $pwd       = $this->request->post('pwd');
            if(!$this->validatePwd($pwd)){
                return json(['status' => 0, 'msg' => '支付密码错误']);
            }
            $currency = config("currency");
            $abonus   = config("abonus");
            $recharge = $this->user['recharge'];
            $account  = Db::name('main_account')->find($id);
            $count    = Db::name('main_account')->where(['user_id' => $this->user['id'], 'status' => 1])->count();
            if (!$account) {
                return json(['status' => 0, 'msg' => '非法操作']);
            }
            if ($account['status'] == '1') {
                return json(['status' => 0, 'msg' => '此账户已激活']);
            }
            if ($count >= $abonus['main_cap']) {
                return json(['status' => 0, 'msg' => '最多激活' . $abonus['main_cap'] . '主账户']);
            }
            if ($account['price'] > $recharge) {
                return json(['status' => 0, 'msg' => $currency['recharge'] . '余额不足']);
            }

            //扣除货币
            $message = "激活主账户【{$account['name']}】扣除{$account['price']}{$currency['recharge']}";
            $result  = dec_money($this->user['id'], $this->user['username'], 'recharge', $account['price'], $message, 1);
            if (!$result) {
                return json(['status' => 0, 'msg' => '激活失败']);
            }

            //奖励上级直推
            if ($this->user['invite']) {
                $invite = Db::name('user')->find($this->user['invite']);
                if ($invite['status'] == 1 && $abonus['main_invite'] > 0) {

                    Db::name('main_account')->where(['status'=>1,'user_id'=>$invite['id']])->setInc('invite', $abonus['main_invite']);
                    
                    // $message = "推荐用户 {$this->user['username']} 激活主账户【{$account['name']}】直推奖励";
                    // inc_money($invite['id'], $invite['username'], 'money', $abonus['main_invite'], $message, 2);
                }
            }

            //增加分红基金
            Db::name('fund')->where('1=1')->setInc('abonus', $abonus['main_abonus']);
            //增加慈善基金
            Db::name('fund')->where('1=1')->setInc('charity', $abonus['main_charity']);

            //更新为激活状态
            Db::name('main_account')->where('id', $id)->update(['status' => 1, 'time' => time()]);
            return json(['status' => 1, 'msg' => '激活成功']);
        } else {
            $this->setPayPwd($this->request->url(true));
            $accounts = Db::name('main_account')->where('user_id', $this->user['id'])->order('status ASC, id ASC')->paginate(17);
            $this->assign('accounts', $accounts);
            return $this->fetch();
        }
    }

    //子账户列表
    public function son()
    {
        $this->setPayPwd($this->request->url(true));
        $accounts = Db::name('son_account')->where('user_id', $this->user['id'])->order('id DESC')->paginate(10);
        $this->assign('accounts', $accounts);
        return $this->fetch();
    }

    //购买子账户
    public function buySon()
    {
        $config = config("abonus");
        $myNum  = Db::name('son_account')->where(['user_id' => $this->user['id'], 'status' => 1])->sum('num');
        if ($this->request->isAjax()) {
            $input = $this->request->post();
            if(!$this->validatePwd($input['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            if ($this->verifyToken($input['__token__']) === false) {
                return json(['success' => 0, 'msg' => '令牌错误']);
            }
            if (!$input['num']) {
                return json(['success' => 0, 'msg' => '请输入购买数量']);
            }
            if (strpos($input['num'], '.') !== false) {
                return json(['success' => 0, 'msg' => '请输入一个整数']);
            }
            if ($myNum >= $config['son_cap']) {
                return json(['success' => 0, 'msg' => '最多拥有' . $config["son_cap"] . '个复投账户']);
            }
            if ($config['son_switch']) {
                $mainCount = Db::name('main_account')->where(['user_id' => $this->user['id'], 'status' => 1])->count();
                if ($mainCount < $config['main_cap']) {
                    return json(['success' => 0, 'msg' => '主账户需全部激活之后才可以购买复投账户']);
                }
            }
            $recharge = $this->user['recharge']; //用户充值币数量
            $currency = config("currency"); //货币名字配置
            if ($config['son_price'] > $recharge) {
                return json(['success' => 0, 'msg' => $currency['recharge'] . '余额不足']);
            }
            //扣除货币
            $money   = $input['num'] * $config['son_price'];
            $message = "购买{$input['num']}个复投账户，扣除{$money}{$currency['recharge']}";
            $result  = dec_money($this->user['id'], $this->user['username'], 'recharge', $money, $message, 1);
            if (!$result) {
                return json(['success' => 0, 'msg' => '购买失败']);
            }
            //购买奖励游戏币
            if ($config['son_game']) {
                $buyGame = $config['son_game'] * $input['num'];
                $message  = "购买{$input['num']}个复投账户奖励{$buyGame}";
                inc_money($this->user['id'], $this->user['username'], 'game', $buyGame, $message, 3);
            }
            //购买奖励购物币
            if ($config['son_shopping']) {
                $buySopping = $config['son_shopping'] * $input['num'];
                $message  = "购买{$input['num']}个复投账户奖励{$buySopping}";
                inc_money($this->user['id'], $this->user['username'], 'game', $buySopping, $message, 3);
            }
            //上级直推奖励
            if ($this->user['invite']) {
                $invite = Db::name('user')->find($this->user['invite']);
                if ($invite['status'] == 1 && $config['son_invite'] > 0) {
                    $inviteMoney = $config['son_invite'] * $input['num'];
                    Db::name('main_account')->where(['status'=>1,'user_id'=>$invite['id']])->setInc('invite', $inviteMoney);
                    //$message     = "推荐用户 {$this->user['username']} 购买{$input['num']}个复投账户直推奖励";
                    //inc_money($invite['id'], $invite['username'], 'money', $inviteMoney, $message, 2);
                }
            }
            //增加分红基金
            Db::name('fund')->where('1=1')->setInc('abonus', $config['son_abonus']);
            //增加慈善基金
            Db::name('fund')->where('1=1')->setInc('charity', $config['son_charity']);

            //添加复投账户
            Db::name('son_account')->insert([
                'username' => $this->user['username'],
                'user_id'  => $this->user['id'],
                'price'    => $config['son_price'],
                'num'      => intval($input['num']),
                'status'   => 1,
                'time'     => time(),
            ]);
            return json(['success' => 1, 'msg' => '购买成功', 'url' => url('index/account/son')]);
        } else {
            $this->assign('config', $config);

            $this->assign('myNum', $myNum ? $myNum : 0);
            return $this->fetch('buy');
        }
    }

    //账户明细
    public function record()
    {
        $type             = $this->request->get('type');
        $where['user_id'] = $this->user['id'];
        if ($type) {
            $record = Db::name('money_record')->where($where)->where('money', '>', 0)->order('id DESC')->paginate(15, false, ['query' => ['type' => 1]]);
        } else {
            $record = Db::name('money_record')->where($where)->where('money', '<', 0)->order('id DESC')->paginate(15, false, ['query' => ['type' => 0]]);
        }
        $this->assign('record', $record);
        $this->assign('currency', config('currency'));
        return $this->fetch();
    }

    //每日市场记录
    public function daily()
    {
        $data   = [];
        $result = Db::name('day_record')->order('date DESC')->limit(10)->select();
        $result = array_reverse($result);
        if ($result) {
            foreach ($result as $v) {
                $data['date'][]  = date('m-d', $v['date']);
                $data['price'][] = $v['price'];
            }
        }
        $this->assign('data', json_encode($data));
        return $this->fetch();
    }

    //收分红币
    public function getMoney()
    {
        if ($this->request->isAjax()){
            $post = $this->request->post();
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            $config = config('abonus');
            $currency = config("currency");
            if($post['num'] < $config['full_money']){
                return json(['success' => 0, 'msg' => '数量不能低于'.$config['full_money'].'个']);
            }
            if(isset($post['type'])){
                $db = Db::name('main_account');
                $row = $db->find($post['id']);
                $message = "我的账户：{$row['name']} 收分红奖 {$post['num']} 个 {$currency['money']}";
            }else{
                $db = Db::name('son_account');
                $row = $db->find($post['id']);
                $message = "复投账户ID：{$row['id']} 收分红奖 {$post['num']} 个 {$currency['money']}";
            }
            if(!$row || $row['user_id'] != $this->user['id']){
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            if($row['balance'] < $post['num']){
                return json(['success' => 0, 'msg' => '余额不足']);
            }
            $result = $db->where('id',$row['id'])->setDec('balance',$post['num']);
            if(!$result){
                return json(['success' => 0, 'msg' => '操作失败，请重试']);
            }
            inc_money($this->user['id'],$this->user['username'],'money',$post['num'],$message,17);
            return json(['success' => 1, 'msg' => '操作成功']);
        }
    }

    //收充值币
    public function getRecharge()
    {
        if ($this->request->isAjax()){
            $post = $this->request->post();

            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            $config = config('abonus');
            $currency = config("currency");
            if($post['num'] < $config['full_recharge']){
                return json(['success' => 0, 'msg' => '数量不能低于'.$config['full_recharge'].'个']);
            }
            if(isset($post['type'])){
                $db = Db::name('main_account');
                $row = $db->find($post['id']);
                $message = "我的账户：{$row['name']} 收分红奖 {$post['num']} 个 {$currency['recharge']}";
            }else{
                $db = Db::name('son_account');
                $row = $db->find($post['id']);
                $message = "复投账户ID：{$row['id']} 收分红奖 {$post['num']} 个 {$currency['recharge']}";
            }
            if(!$row || $row['user_id'] != $this->user['id']){
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            if($row['balance'] < $post['num']){
                return json(['success' => 0, 'msg' => '余额不足']);
            }
            $result = $db->where('id',$row['id'])->setDec('balance',$post['num']);
            if(!$result){
                return json(['success' => 0, 'msg' => '操作失败，请重试']);
            }
            inc_money($this->user['id'],$this->user['username'],'recharge',$post['num'],$message,17);
            return json(['success' => 1, 'msg' => '操作成功']);
        }
    }

    //一键收币
    public function onekey()
    {
        if ($this->request->isAjax()){
            $post = $this->request->post();
            //判断支付密码
            if(!$this->validatePwd($post['pwd'])){
                return json(['success' => 0, 'msg' => '支付密码错误']);
            }
            if(empty($post['type']) || !isset($post['diff'])){
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            $config = config('abonus');
            $currency = config("currency");
            if($post['diff']){
                $db = Db::name('main_account');
                $accountName = '我的账户:';
            }else{
                $db = Db::name('son_account');
                $accountName = '复投账户ID：';
            }
            $field = 'balance'; //默认余额字段
            $currencyName = 'money'; //默认提现币
            $currencyType = 17; //默认分红奖
            $where['user_id'] = $this->user['id'];
            switch ($post['type']) {
                case '1':
                    //收推荐奖为提现币
                    $where['invite'] = ['EGT',$config['invite_money']];
                    $field = 'invite';
                    $currencyType = 18;
                    $message = $accountName . " %s 收推荐奖 %s 个 {$currency['money']}";
                    break;
                case '2':
                    //收推荐奖为充值币
                    $where['invite'] = ['EGT',$config['invite_recharge']];
                    $field = 'invite';
                    $currencyName = 'recharge';
                    $currencyType = 18;
                    $message = $accountName . " %s 收推荐奖 %s 个 {$currency['recharge']}";
                    break;
                case '3':
                    //收分红奖为提现币
                    $where['balance'] = ['EGT',$config['full_money']];
                    $message = $accountName . " %s 收分红奖 %s 个 {$currency['money']}";
                    break;
                case '4':
                    //收分红奖为充值币
                    $where['balance'] = ['EGT',$config['full_recharge']];
                    $currencyName = 'recharge';
                    $message = $accountName . " %s 收分红奖 %s 个 {$currency['recharge']}";
                    break;
            }
            $accounts = $db->where($where)->select();
            if(!$accounts){
                return json(['success' => 0, 'msg' => '没有可收的啦']);
            }
            $total = 0;
            foreach ($accounts as $v) {
                $money = $v[$field];
                $result = $db->where('id',$v['id'])->setField($field,0);
                if($result){
                    $name = $post['diff'] ? $v['name'] : $v['id'];
                    $msg = sprintf($message,$name,$money);
                    $result2 = inc_money($this->user['id'],$this->user['username'],$currencyName,$money,$msg,$currencyType);
                    if($result2){
                        $total += $money;
                    }
                }
            }
            return json(['success' => 1, 'msg' => '本次总收'.$total.'个']);
        }
    }

}
